package com.yjf.ljr.activity;

import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnDismissListener;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.yjf.ljr.R;
import com.yjf.ljr.adapter.ViewPagerAdapter;
import com.yjf.ljr.common.CommonData;
import com.yjf.ljr.dataclass.HomepgAdvDataClass;
import com.yjf.ljr.dataclass.InvestDetailDataClass;
import com.yjf.ljr.dataclass.HomepgAdvDataClass.HomepgAdvInfo;
import com.yjf.ljr.dataclass.InvestDetailDataClass.ProjectInfo;
import com.yjf.ljr.parser.RequestBuilder.RequestObject;
import com.yjf.ljr.util.AppUtil;
import com.yjf.ljr.util.PicLoad;
import com.yjf.ljr.util.SPreferences;
import com.yjf.ljr.util.ViewPagerScroller;
import com.yjf.ljr.view.RedPacketDialog;
import com.yjf.ljr.view.XListView;
import com.yjf.ljr.view.XListView.IXListViewListener;

/**
 * 投资无忧首页
 * 
 * @author dongxie
 */
public class HomePageActivity extends IjActivity implements OnClickListener {

	public static final int HANDLER_REFRESH_TIME = 1000;

	private AtomicInteger mWhat = new AtomicInteger(0);

	@ID("vpagerAdv")
	private ViewPager mAdvPager;
	@ID("tv_title_right")
	private TextView mTvLogin;

	@ID("xlvHomepg")
	private XListView mXlvHomepg;

	@ID("tvTitleRecommend")
	private TextView mTvTitleRecommend; // 标题
	@ID("tvProjectIncome")
	private TextView mTvProjectIncome; // 预期年化利率
	@ID("tvProjectDate")
	private TextView mTvProjectDate; // 借款期限
	@ID("tvInvestMoneyStart")
	private TextView mTvInvestMoneyStart; // 起投金额
	@ID("tvInvestTimeStart")
	private TextView mTvInvestTimeStart; // 起投时间
	@ID("tvProjectProgress")
	private TextView mTvProjectProgress; // 投资进度
	@ID("tvProjectInvestTimeLimit")
	private TextView mTvProjectInvestTimeLimit;
	@ID("tvCheckDetail")
	private TextView mTvCheckDetail;
	@ID("pbProjectDetail")
	private ProgressBar mPbProjectDetail; // 投资进度
	private long mTimeLeft; // 剩余时间
	private String demandId;// 项目Id
	private String mProjectStatus;
	private boolean mIsLoadingMore = false;
	private String mTradeEffectiveDate;
	private DecimalFormat format;

	private Thread switchBannerThread;
	private List<View> advPics;
	private ViewPagerAdapter bannerAdapter;
	private List<ImageView> mImageViews;

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case HANDLER_REFRESH_TIME:
				String title = "";
				if ("3".equals(mProjectStatus)) { // 未到投资时间
					title = "项目投资开始： ";
				} else if ("1".equals(mProjectStatus)) { // 正在投资
					title = "投资截止时间： ";
				} else if ("2".equals(mProjectStatus)) {// 起息
					AppUtil.setViewText(mTvProjectInvestTimeLimit, "项目起息时间：等待项目审核");
					mHandler.removeMessages(HANDLER_REFRESH_TIME);
					return;
				} else if ("7".equals(mProjectStatus)) {// 起息
					AppUtil.setViewText(mTvProjectInvestTimeLimit, "项目起息时间：" + mTradeEffectiveDate);
					mHandler.removeMessages(HANDLER_REFRESH_TIME);
					return;
				} else {
					mHandler.removeMessages(HANDLER_REFRESH_TIME);
					return;
				}

				if (mTimeLeft > 1) {
					AppUtil.setViewHtml(mTvProjectInvestTimeLimit, title + getTimeStr(mTimeLeft));
					mTimeLeft -= 1;
					mHandler.sendEmptyMessageDelayed(HANDLER_REFRESH_TIME, 1000);
				} else {
					AppUtil.setViewHtml(mTvProjectInvestTimeLimit, "");
					mHandler.removeMessages(HANDLER_REFRESH_TIME);

					// 切换时刷新页面
					showProgressDialog();
					new HomepgRecommendTask().execute();
				}
				break;
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_homepage);

		initControls();
		initPager();
		showProgressDialog();
		new HomepgAdvTask().execute();

	}

	/** 初始化控件 **/
	private void initControls() {
		mTvLogin.setOnClickListener(this);

		View vContent = LayoutInflater.from(this).inflate(R.layout.activity_homepg_header, null);
		initComponents(this, vContent, this);
		format = new DecimalFormat("#.00");
		mXlvHomepg.addHeaderView(vContent);
		mXlvHomepg.setAdapter(null);
		mXlvHomepg.setPullLoadEnable(true);
		mXlvHomepg.setPullRefreshEnable(true);
		mXlvHomepg.setDealScrollConfilct();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		mXlvHomepg.setRefreshTime(sdf.format(new Date()));
		mXlvHomepg.mFooterView.hide(); // 隐藏更多
		mXlvHomepg.setXListViewListener(new IXListViewListener() {
			@Override
			public void onRefresh() {
				if (mIsLoadingMore) {
					return;
				}
				mIsLoadingMore = true;
				new HomepgRecommendTask().execute();
				new HomepgAdvTask().execute();
			}

			@Override
			public void onLoadMore() {
			}
		});
	}

	private void initPager() {
		mImageViews = new ArrayList<ImageView>();
		advPics = new ArrayList<View>();
		bannerAdapter = new ViewPagerAdapter(advPics);

		mAdvPager.setAdapter(bannerAdapter);
//		mAdvPager.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 160));
		mAdvPager.setOnPageChangeListener(new GuidePageChangeListener());

		/** 设置viewpager滑动速度 **/
		try {
			Field mScroller = null;
			mScroller = ViewPager.class.getDeclaredField("mScroller");
			mScroller.setAccessible(true);
			ViewPagerScroller scroller = new ViewPagerScroller(mAdvPager.getContext());
			scroller.setScrollDuration(500);
			mScroller.set(mAdvPager, scroller);
		} catch (Exception e) {
			e.printStackTrace();
		}

		switchBannerThread = new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					mViewHandler.sendEmptyMessage(mWhat.get());
					try {
						Thread.sleep(8000L);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					whatOption();
				}
			}
		});
		switchBannerThread.start();
	}

	private void refreshPager(List<HomepgAdvInfo> mAdList) {
		ViewGroup group = (ViewGroup) findViewById(R.id.viewGroup);
		group.removeAllViews();
		mImageViews.clear();
		advPics.clear();
		if (mAdList != null && mAdList.size() > 0) {
			for (int i = 0; i < mAdList.size(); i++) {
				advPics.add(getImageView(mAdList.get(i)));
			}
			for (int i = 0; i < advPics.size(); i++) {
				ImageView iv = new ImageView(this);
				iv.setLayoutParams(new LayoutParams(20, 20));
				iv.setPadding(5, 5, 5, 5);
				mImageViews.add(iv);
				if (i == mWhat.get()) {
					mImageViews.get(i).setBackgroundResource(R.drawable.dot_adv_focus);
				} else {
					mImageViews.get(i).setBackgroundResource(R.drawable.dot_adv);
				}
				group.addView(mImageViews.get(i));
			}
		}
		bannerAdapter.notifyDataSetChanged();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (CommonData.FLAG_LOGIN_SERVER) {
			// mTvLogin.setVisibility(View.GONE);
			mTvLogin.setText("已登录");
			mTvLogin.setEnabled(false);
			CommonData.FLAG_LOGIN_SERVER = false;
			MyAccountActivity.gIsLoginServer = true;
		} else {
			mTvLogin.setText("登录");
			mTvLogin.setEnabled(true);
		}
		super.onActivityResult(requestCode, resultCode, intent);
	}

	@Override
	protected void onResume() {
		// mTvLogin.setVisibility(MyAccountActivity.gIsLoginServer ? View.GONE :
		// View.VISIBLE);
		if (MyAccountActivity.gIsLoginServer) {
			mTvLogin.setText("已登录");
			mTvLogin.setEnabled(false);
		} else {
			mTvLogin.setText("登录");
			mTvLogin.setEnabled(true);
		}
		showProgressDialog();
		new HomepgRecommendTask().execute();
		super.onResume();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_title_right: // 登录
			loginWebview();
			break;
		}
	}

	private void whatOption() {
		mWhat.incrementAndGet();
		if (mWhat.get() > mImageViews.size() - 1) {
			mWhat.getAndSet(0);
		}
	}

	private final Handler mViewHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (msg.what >= 0 && msg.what < advPics.size())
				mAdvPager.setCurrentItem(msg.what);
			super.handleMessage(msg);
		}
	};

	private final class GuidePageChangeListener implements OnPageChangeListener {

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageSelected(int arg0) {
			mWhat.getAndSet(arg0);
			for (int i = 0; i < mImageViews.size(); i++) {
				mImageViews.get(arg0).setBackgroundResource(R.drawable.dot_adv_focus);
				if (arg0 != i) {
					mImageViews.get(i).setBackgroundResource(R.drawable.dot_adv);
				}
			}
		}
	}

	private ImageView getImageView(final HomepgAdvInfo advInfo) {
		ImageView iv = new ImageView(this);
		iv.setScaleType(ScaleType.CENTER_CROP);
		iv.setImageResource(R.drawable.banner_default);
		iv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (!TextUtils.isEmpty(advInfo.linkUrl)) {
					Intent i = new Intent(HomePageActivity.this, AdvActivity.class);
					i.putExtra("advUrl", advInfo.linkUrl);
					i.putExtra("advTitle", "新闻公告");
					startActivity(i);
				}
			}
		});

		// 加载网络图片
		if (!TextUtils.isEmpty(advInfo.imgUrl)) {
			PicLoad.getImage(iv, "", advInfo.imgUrl);
		}
		return iv;
	}

	class HomepgAdvTask extends AsyncTask<Void, Void, String> {

		private HomepgAdvDataClass dc = new HomepgAdvDataClass();

		@Override
		protected String doInBackground(Void... params) {
			RequestObject reqObj = new RequestObject();
			reqObj.method = "getIndexImg";
			return requestDataAndGetErrorMsg(reqObj, dc);
		}

		@Override
		protected void onPostExecute(String result) {
			if (!TextUtils.isEmpty(result)) {
				showToast(result);
			} else {
				if (dc.picList != null && dc.picList.size() > 0) {
					refreshPager(dc.picList);
				}
			}
			dismissProgressDialog();
		}
	}

	class HomepgRecommendTask extends AsyncTask<Void, Void, String> {

		private InvestDetailDataClass dc = new InvestDetailDataClass();

		@Override
		protected String doInBackground(Void... params) {
			RequestObject reqObj = new RequestObject();
			reqObj.method = "appProjectList";
			reqObj.map.put("pageSize", 1);
			reqObj.map.put("pageNumber", 1);
			reqObj.map.put("status", 1);
			return requestDataAndGetErrorMsg(reqObj, dc);
		}

		@Override
		protected void onPostExecute(String result) {
			if (!TextUtils.isEmpty(result)) {
				showToast(result);
			} else {
				if (dc.projectList != null && dc.projectList.size() > 0) {
					ProjectInfo info = dc.projectList.get(0);
					AppUtil.setViewText(mTvTitleRecommend, info.loanName);
					AppUtil.setViewText(mTvProjectIncome, info.interestRate);
					String strProgressStr = info.interestRate;
//					SpannableStringBuilder style = new SpannableStringBuilder(strProgressStr);
//					style.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.orange_text_content)), 0, strProgressStr.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//					style.setSpan(new ForegroundColorSpan(Color.BLACK), strProgressStr.length() - 1, strProgressStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//					style.setSpan(new AbsoluteSizeSpan(60),strProgressStr.length() - 1, strProgressStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//					mTvProjectIncome.setText(style);
					mTvProjectIncome.setText(strProgressStr);
					AppUtil.setViewText(mTvProjectDate, info.timeLimit+"投资期限");
					AppUtil.setViewText(mTvProjectDate, info.timeLimit);
//					AppUtil.setViewText(mTvInvestMoneyStart, info.leastInvestAmount);
					if (info.avalableAmount != null && !info.avalableAmount.equals("")) {
						String amount = info.avalableAmount.replace(",", "");
						amount = amount.substring(0, amount.indexOf("."));
						int acalableAmount = Integer.parseInt(amount);
						if ( acalableAmount >= 10000) {
							AppUtil.setViewText(mTvInvestMoneyStart, acalableAmount/10000+"万");
						} else {
							AppUtil.setViewText(mTvInvestMoneyStart, acalableAmount/10000+"元");
						}
					}
					AppUtil.setViewText(mTvInvestTimeStart, info.investAvlDate);
					demandId = info.demandId;
					mProjectStatus = info.status;
					mTimeLeft = info.leftTime;
					mTradeEffectiveDate = info.tradeEffectiveDate;
					mHandler.removeMessages(HANDLER_REFRESH_TIME);
					mHandler.sendEmptyMessage(HANDLER_REFRESH_TIME);

					/** 进度条 **/
					if (!TextUtils.isEmpty(info.investProgress)) {
						double progress = 0;
						try {
							String strProgress = info.investProgress;
							if (strProgress.endsWith("%")) {
								strProgress = strProgress.substring(0, strProgress.length() - 1);
							}
							progress = Double.parseDouble(format.format(Double.parseDouble(strProgress)));
						} catch (Exception e) {
							e.printStackTrace();
						}
						mPbProjectDetail.setProgress((int) (progress));
						String investRate = dealTwoDecimalPlaces(progress);
						AppUtil.setViewText(mTvProjectProgress, investRate + "%");
					}

					mTvCheckDetail.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							Intent i = new Intent(HomePageActivity.this, ProjectDetailActivity.class);
							i.putExtra("demandId", demandId);
							startActivity(i);

						}
					});
				}
			}
			dismissProgressDialog();
			mXlvHomepg.stopRefresh();
			mXlvHomepg.stopLoadMore();
			mIsLoadingMore = false;
		}
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
		return false;
	}

	public static String getTimeStr(long inTimeInMillis) {
		long day = inTimeInMillis / (3600 * 24);
		long hour = inTimeInMillis % (3600 * 24);
		long leftSeconds = hour % 3600;
		return "<font color='#F47A0E'>" + day + "</font>天" + "<font color='#F47A0E'> " + hour / 3600 + "</font>时"
				+ "<font color='#F47A0E'> " + leftSeconds / 60 + "</font>分" + "<font color='#F47A0E'> " + leftSeconds
				% 60 + "</font>秒";
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (switchBannerThread != null) {
			try {
				switchBannerThread.interrupt();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**** 处理为两位小数 ***/
	private String dealTwoDecimalPlaces(double str) {
		DecimalFormat df = new DecimalFormat("#.00");
		String temp2;
		String temp;
		double progress = str;
		temp = df.format(progress);
		if ("0".equals("" + temp.indexOf("."))) {
			temp = "0" + temp;
		}
		if (!("-1".equals(temp.indexOf(".")))) {
			String aaString = temp.substring(temp.indexOf(".") + 1, temp.length());
			if ("0".equals(temp.substring(temp.indexOf(".") + 1, temp.length()))) {
				temp2 = temp.substring(0, temp.indexOf("."));
			} else {
				temp2 = temp;
			}
		} else {
			temp2 = temp;
		}

		return temp2;
	}
}
